import { Form, Input, Button, Upload, message } from "antd";
import { Component, ReactNode } from "react";
import { Editor } from "react-draft-wysiwyg";
import { EditorState, convertToRaw } from "draft-js";
import draftToHtml from "draftjs-to-html";
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";
import { UploadOutlined } from "@ant-design/icons";
import { instance } from '../../utils/request';

interface AddGoodFormProps {
  visible?: boolean;
  close?: () => void;
  closeModal: () => void; // 将closeModal方法作为props传递给子组件
}

class AddGoodForm extends Component<AddGoodFormProps> {
  state = {
    // 富文本存储的值
    editorText: '',
  };
  onFinish = (values: any) => {
    console.log(values);
    let params = {
      goods_name: values.goods_name,
      goods_price: values.goods_price,
      goods_number: values.goods_number,
      goods_weight: values.goods_weight,
      goods_cat: "1,2,3",
      // 富文本信息
      goods_introduce: this.state.editorText,
      goods_small_logo:values.goods_small_logo[0].response.data.data.url
    };
    instance
      .post("/goods", params)
      .then((res) => {
        message.success("添加商品成功!");
        this.props.closeModal();
      })
      .catch((error) => {
        console.log("error=", error);
      });
  };

  handleCustomRequest = (options:any) => {
    const { file, onError, onSuccess } = options;
    const ext = file.name.split('.')[1];
    if (!['jpg', 'jpeg', 'png'].includes(ext)) {
      message.error('请上传jpg、jpeg、png格式的图片');
      onError('File format not supported');
      return;
    }

    const formData = new FormData();
    formData.append('file', file);

    instance.post("/upload", formData)
      .then((response) => {
        onSuccess(response, file);
      })
      .catch((error) => {
        onError(error);
      });
  };

  
  onFinishFailed = () => {};
  normFile = (e: any) => {
    console.log("Upload event:", e);
    if (Array.isArray(e)) {
      return e;
    }
    return e?.fileList;
  };

  onEditorStateChange = (editorState: any) => {
    let html = draftToHtml(convertToRaw(editorState.getCurrentContent()));
    this.setState({ editorText: html });
  };

  render() {
    return (
      <div>
        <Form onFinish={this.onFinish} onFinishFailed={this.onFinishFailed}>
          <Form.Item
            label="商品名称"
            name="goods_name"
            rules={[{ required: true, message: "请输入商品名称" }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="商品价格"
            name="goods_price"
            rules={[{ required: true, message: "请输入商品价格" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="商品重量"
            name="goods_weight"
            rules={[{ required: true, message: "请输入商品重量" }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="商品数量"
            name="goods_number"
            rules={[{ required: true, message: "请输入商品数量" }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="商品图片"
            name="goods_small_logo"
            rules={[{ required: true, message: "请上传商品图片" }]}
            valuePropName="fileList"
            getValueFromEvent={this.normFile}
          >
            <Upload
             customRequest={this.handleCustomRequest}
              listType="picture"
            >
              <Button icon={<UploadOutlined />}>上传图片</Button>
            </Upload>
          </Form.Item>

          <Form.Item
            label="商品详情"
            name="goods_introduce"
            rules={[
              {
                validator: (rule, value, callback) => {
                  const content = this.state.editorText
                  console.log(content,'1----')
                  if (content!=='') {
                    callback();
                  } else {
                    callback("请输入商品详情");
                  }
                },
              },
            ]}
          >
           <div  className="editor-container">
              <Editor
                toolbarClassName="toolbarClassName"
                wrapperClassName="wrapperClassName"
                editorClassName="editorClassName"
                onEditorStateChange={this.onEditorStateChange}
              />
            </div>
          </Form.Item>

          <Form.Item style={{float:'right',marginLeft:'10px'}}>
            <Button type="primary" htmlType="submit">
              提交
            </Button>
          </Form.Item>
        </Form>
      </div>
    );
  }
}

export default AddGoodForm;
